//
//  21. 合并两个有序链表.swift
//  Top600
//
//  Created by rjb on 2021/8/8.
//

import Foundation
class Solution21 {
    // 合并两个有链表
    func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let vHead: ListNode? = ListNode(0)
        var p = vHead
        var p1 = l1
        var p2 = l2
        while p1 != nil && p2 != nil {
            if p1!.val <= p2!.val {
                p?.next = p1
                p1 = p1?.next
                
                p = p?.next
            } else {
                p?.next = p2
                p2 = p2?.next
                
                p = p?.next
            }
        }
        if p1 != nil {
            p?.next = p1
        }
        if p2 != nil {
            p?.next = p2
        }
        return vHead?.next
    }
    static func test() {
       let solution = Solution21()
        let node1 = ListNode(1)
        let node2 = ListNode(2)
        let node4 = ListNode(4)
        node1.next = node2
        node2.next = node4
        
        let node11 = ListNode(1)
        let node33 = ListNode(3)
        let node44 = ListNode(4)
        node11.next = node33
        node33.next = node44
        
        let result = solution.mergeTwoLists(node1, node11)
        print(result)
    }
}
